package com.example.webwork.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.webwork.entity.Contact;
import com.example.webwork.mapper.ContactMapper;
import com.example.webwork.service.IContactService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ContactServiceImpl extends ServiceImpl<ContactMapper, Contact> implements IContactService {

    @Override
    public List<Contact> getAllContacts(String username) {
        return list(new QueryWrapper<Contact>().eq("username", username));
    }

    @Override
    public void saveContact(Contact contact) {
        //LambdaQueryWrapper<Contact> queryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Contact> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Contact::getUsername, contact.getUsername())
                .eq(Contact::getName, contact.getName());

        // 执行查询
        Contact existingContact = getOne(queryWrapper);

        if (existingContact != null) {
            // 如果找到匹配的记录，则更新该记录
            contact.setId(existingContact.getId()); // 设置要更新的记录的 ID
            updateById(contact);
        } else {
            // 如果没有找到匹配的记录，则插入新的联系人
            save(contact);
        }

    }

    @Override
    public void updateContact(Contact contact) {
        updateById(contact);
    }

    @Override
    public void deleteContact(Contact contact) {
        LambdaQueryWrapper<Contact> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Contact::getUsername, contact.getUsername())
                .eq(Contact::getName, contact.getName());

        // 执行查询
        Contact existingContact = getOne(queryWrapper);
        if (existingContact != null) {
            // 如果找到匹配的记录，则更新该记录
            Long id = existingContact.getId();
            removeById(id);
        } else {
            // 如果没有找到匹配的记录，则插入新的联系人
            save(contact);
        }

    }
    @Override
    public List<Contact> searchContacts(String username, String name) {
        QueryWrapper<Contact> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);

        if (name != null && !name.trim().isEmpty()) {
            queryWrapper.like("name", name);  // 模糊匹配
        }

        return list(queryWrapper);
    }

}